﻿using MediatR;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.JobCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.JobCommandHandler
{
    public class JobQueryCommandHandler : IRequestHandler<JobQueryCommand, APIResult<APIPaing<Job>>>
    {
        private readonly IBaseRepository<Job> jobRepository;

        public JobQueryCommandHandler(IBaseRepository<Job> jobRepository)
        {
            this.jobRepository = jobRepository;
        }

        public async Task<APIResult<APIPaing<Job>>> Handle(JobQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaing<Job>> result = new APIResult<APIPaing<Job>>();
            var entity = jobRepository.GetAll().Result.Where(x => x.IsDelete == 0);
            if(!string.IsNullOrEmpty(request.JobName))
            {
                entity=entity.Where(x=>x.JobName.Contains( request.JobName));
            }
            if (!string.IsNullOrEmpty(request.JobNode))
            {
                entity = entity.Where(x => x.JobNode==request.JobNode);
            }
            if (request.ApprovalStatus!=null)
            {
                entity = entity.Where(x => x.ApprovalStatus==request.ApprovalStatus);
            }
            if (!string.IsNullOrEmpty(request.JobType))
            {
                entity = entity.Where(x => x.JobType == request.JobType);
            }
            int TotalCount = entity.Count();
            int PageCount = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            entity = entity.OrderByDescending(x => x.JId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
          
            APIPaing<Job> paing = new APIPaing<Job>();
            paing.TotalCount = TotalCount;
            paing.PageCount = PageCount;
            paing.Items=entity.ToList();
            result.Code = APIEnums.查询成功;
            result.Msg=APIEnums.查询成功.ToString();
            result.data = paing;
            return await Task.FromResult(result);
        }
    }
}
